package com.bestcem.xm.wallet.grpc.client;

import cn.hutool.core.lang.ObjectId;
import com.bestcem.bp.xm.user.grpc.v1.services.ListOrgCustomSettingsRequest;
import com.bestcem.bp.xm.user.grpc.v1.services.ListOrgCustomSettingsResponse;
import com.bestcem.bp.xm.user.grpc.v1.services.OrgCustomSetting;
import com.bestcem.bp.xm.user.grpc.v1.services.OrgCustomSettingServiceGrpc;
import com.bestcem.xm.common.core.constant.GrpcClientNames;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

import static com.bestcem.bp.grpc.v1.base.Code.ERROR;

/**
 * 租户自定义配置，向python查询
 *
 * @author likunlei
 * @since 2022/5/17
 * Copyright: 2022 www.bestcem.com. All rights reserved.
 */
@Slf4j
@Component
public class UserCustomSettingGrpcService {

    @GrpcClient(GrpcClientNames.DS_USER)
    private OrgCustomSettingServiceGrpc.OrgCustomSettingServiceBlockingStub stub;

    /**
     * 向python查询租户自定义域名
     *
     * @param orgId 租户id
     */
    public OrgCustomSetting queryCustomSettingByOrgId(String orgId) {
        if (!ObjectId.isValid(orgId)) {
            log.error("[Common] 查询租户自定义配置orgId错误 {}", orgId);
            return null;
        }

        ListOrgCustomSettingsRequest.Builder builder = ListOrgCustomSettingsRequest.newBuilder();
        builder.setEnable(true);
        builder.setOrgId(orgId);
        ListOrgCustomSettingsRequest request = builder.build();

        try {
            ListOrgCustomSettingsResponse response = stub.listOrgCustomSettings(request);
            if (Objects.isNull(response) || ERROR.equals(response.getStatus().getCode())) {
                log.error("[Common] queryCustomSettingByOrgId {} Error; ErrorMsg: {}", orgId, response);
                return null;
            }
            List<OrgCustomSetting> list = response.getSettingsList();
            if (CollectionUtils.isNotEmpty(list)) {
                return list.get(0);
            }
        } catch (Exception e) {
            log.error("[Common] queryCustomSettingByOrgId {} Error;", orgId);
            return null;
        }
        return null;
    }
}
